# main.py
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
from typing import List, Optional
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles  # 添加此导入
import os  # 添加此导入

# 创建 FastAPI 应用实例
app = FastAPI(title="Fly影业电影信息管理系统", description="实现电影数据的增删改查操作")

# 跨域中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录以支持本地海报图片
os.makedirs("src/assets/movie_posters", exist_ok=True)
app.mount("/src/assets/movie_posters", StaticFiles(directory="src/assets/movie_posters"), name="posters")

# 电影数据模型
class Movie(BaseModel):
    id: Optional[int] = Field(None, description="电影ID")
    name: str = Field(..., min_length=1, max_length=100, description="电影名称")
    poster: Optional[str] = Field(None, description="电影海报URL")
    director: str = Field(..., min_length=1, max_length=50, description="导演")
    actors: str = Field(..., description="主演")
    release_date: str = Field(..., description="上映时间")

# 模拟数据库存储
movies_db = [
    Movie(id=1, name="F1：狂飙飞车", poster="/src/assets/movie_posters/F1.webp",
          director="约瑟夫·科辛斯基", actors="布拉德·皮特, 达姆森·伊德瑞斯", release_date="2025-06-27"),
    Movie(id=2, name="名侦探柯南：独眼的残像", poster="/src/assets/movie_posters/kenan.webp",
          director="重原克也", actors="高山南,山崎和佳奈,小山力也,速水奖,高田裕司 ", release_date="2025-06-27"),
    Movie(id=3, name="小小的我", poster="/src/assets/movie_posters/xiaoxiao.webp",
          director="杨荔钠", actors="易烊千玺", release_date="2024-12-27"),
    Movie(id=4, name="那个不为人知的故事", poster="/src/assets/movie_posters/nage.webp",
          director="张岩", actors="邱泽，朗月婷", release_date="2024-11-09"),
    Movie(id=5, name="唐探1900", poster="/src/assets/movie_posters/tangtan1900.webp",
          director="陈思诚", actors="王宝强，刘昊然", release_date="2024-12-27"),
    Movie(id=6, name="唐人街探案3 ", poster="/src/assets/movie_posters/tangtan3.webp",
          director="陈思诚", actors="王宝强，刘昊然", release_date="2024-12-27")
]
next_id = 7

# 创建电影 (Create)
@app.post("/movies/", response_model=Movie, status_code=status.HTTP_201_CREATED, summary="创建电影")
async def create_movie(movie: Movie):
    """
    创建新电影

    - **name**: 电影名称，必需
    - **poster**: 电影海报URL，可选
    - **director**: 导演，必需
    - **actors**: 主演，必需
    - **release_date**: 上映时间，必需
    """
    global next_id

    # 检查电影名称是否已存在
    for existing_movie in movies_db:
        if existing_movie.name == movie.name:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="电影名称已存在"
            )

    # 创建新电影
    new_movie = Movie(
        id=next_id,
        name=movie.name,
        poster=movie.poster,
        director=movie.director,
        actors=movie.actors,
        release_date=movie.release_date
    )
    movies_db.append(new_movie)
    next_id += 1
    return new_movie

# 获取所有电影 (Read)
@app.get("/movies/", response_model=List[Movie], summary="获取所有电影")
async def get_movies(skip: int = 0, limit: int = 100):
    """
    获取电影列表，支持分页

    - **skip**: 跳过的记录数，默认为0
    - **limit**: 返回的记录数，默认为100
    """
    return movies_db[skip: skip + limit]

# 根据ID获取单个电影 (Read)
@app.get("/movies/{movie_id}", response_model=Movie, summary="根据ID获取电影")
async def get_movie(movie_id: int):
    """
    根据电影ID获取电影信息

    - **movie_id**: 电影的唯一标识符
    """
    for movie in movies_db:
        if movie.id == movie_id:
            return movie
    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail="电影未找到"
    )

# 根据名称搜索电影 (Read)
@app.get("/movies/search/{keyword}", response_model=List[Movie], summary="根据名称搜索电影")
async def search_movies(keyword: str):
    """
    根据关键词模糊搜索电影名称

    - **keyword**: 搜索关键词
    """
    result = []
    for movie in movies_db:
        if keyword.lower() in movie.name.lower():
            result.append(movie)
    return result

# 更新电影信息 (Update)
@app.put("/movies/{movie_id}", response_model=Movie, summary="更新电影信息")
async def update_movie(movie_id: int, movie_update: Movie):
    """
    根据电影ID更新电影信息

    - **movie_id**: 电影的唯一标识符
    - **movie_update**: 更新的电影信息
    """
    for index, movie in enumerate(movies_db):
        if movie.id == movie_id:
            # 检查电影名称是否被其他电影使用
            for existing_movie in movies_db:
                if existing_movie.id != movie_id and existing_movie.name == movie_update.name:
                    raise HTTPException(
                        status_code=status.HTTP_400_BAD_REQUEST,
                        detail="电影名称已存在"
                    )

            # 更新电影信息
            updated_movie = Movie(
                id=movie_id,
                name=movie_update.name,
                poster=movie_update.poster,
                director=movie_update.director,
                actors=movie_update.actors,
                release_date=movie_update.release_date
            )
            movies_db[index] = updated_movie
            return updated_movie

    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail="电影未找到"
    )

# 删除电影 (Delete)
@app.delete("/movies/{movie_id}", status_code=status.HTTP_204_NO_CONTENT, summary="删除电影")
async def delete_movie(movie_id: int):
    """
    根据电影ID删除电影

    - **movie_id**: 电影的唯一标识符
    """
    for index, movie in enumerate(movies_db):
        if movie.id == movie_id:
            movies_db.pop(index)
            return

    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail="电影未找到"
    )

# 启动服务器
if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
